/**
 * Copyright 2009 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.sapien.dao.jpa;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;

import com.google.code.sapien.dao.EntityDAO;

/**
 * Abstract JPA DAO, contains default implementation of the {@link com.google.code.sapien.dao.EntityDAO}
 * interface as well as helper methods for interacting with the JPA API.
 * @author adam
 * @version $Id$
 * 
 * Created on May 5, 2009 at 6:23:08 PM
 * @param <T> The entity data model class type.
 */
public abstract class AbstractJpaDAO<T> implements EntityDAO<T> {
    /**
     * JPA Entity Manager.
     */
    private final EntityManager entityManager;

    /**
     * The persistent class.
     */
    private final Class<T> persistentClass;

	/**
     * AbstractJpaDAO constructor.
     */
    @SuppressWarnings("unchecked")
	public AbstractJpaDAO(final EntityManager entityManager) {
    	this.entityManager = entityManager;
    	this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
    }

	/**
	 * {@inheritDoc}
	 * @see com.google.code.sapien.dao.EntityDAO#add(java.lang.Object)
	 */
	public void add(final T entity) {
		entityManager.persist(entity);
	}

    /**
	 * {@inheritDoc}
	 * @see com.google.code.sapien.dao.EntityDAO#get(java.io.Serializable)
	 */
	public T get(final Serializable id) {
		return entityManager.find(persistentClass, id);
	}

	/**
	 * Returns entityManager.
	 * @return the entityManager.
	 */
	public EntityManager getEntityManager() {
		return entityManager;
	}

	/**
	 * Returns persistentClass.
	 * @return the persistentClass.
	 */
	public Class<T> getPersistentClass() {
		return persistentClass;
	}

	/**
	 * {@inheritDoc}
	 * @see com.google.code.sapien.dao.EntityDAO#load(java.io.Serializable)
	 */
	public T load(final Serializable id) {
		return entityManager.getReference(persistentClass, id);
	}

	/**
	 * {@inheritDoc}
	 * @see com.google.code.sapien.dao.EntityDAO#remove(java.lang.Object)
	 */
	public void remove(final T entity) {
		entityManager.remove(entity);
	}

	/**
	 * {@inheritDoc}
	 * @see com.google.code.sapien.dao.EntityDAO#update(java.lang.Object)
	 */
	public T update(final T entity) {
		return entityManager.merge(entity);
	}
}
